package com.thermofisher.dsc.amanda.security.handler;

import com.thermofisher.dsc.amanda.common.exception.BaseException;
import com.thermofisher.dsc.amanda.common.exception.ExceptionCode;
import com.thermofisher.dsc.amanda.model.response.BaseResponse;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice("com.thermofisher.dsc.biologicprofile")
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(BaseException.class)
    public BaseResponse baseExceptionHandler(HttpServletResponse response, BaseException ex) {
        return new BaseResponse(ex.getStatus(), ex.getMessage() + "");
    }

    @ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResponse handleBindException(Exception e) {
        //Hibernate Validator验证消息返回
        BindingResult result = null;
        List<String> errorMessage = new ArrayList<>();
        if (e instanceof MethodArgumentNotValidException) {
            result = ((MethodArgumentNotValidException) e).getBindingResult();
            result.getFieldErrors().stream().forEach(fieldError ->
                errorMessage.add(fieldError.getDefaultMessage())
            );
        } else if (e instanceof BindException) {
            result = ((BindException) e).getBindingResult();
            result.getFieldErrors().stream().forEach(fieldError ->
                errorMessage.add(fieldError.getDefaultMessage())
            );
        }
        StringBuffer sb = new StringBuffer();
        errorMessage.forEach(message ->sb.append(message+", "));

        return new BaseResponse(ExceptionCode.BED_REQUEST, 2, sb.toString());
    }
}
